package com.example.tencentdemo.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.example.tencentdemo.entity.ChatGroup;
import com.example.tencentdemo.entity.admin_message;
import com.example.tencentdemo.service.Impl.ChatGroupImpl;
import com.example.tencentdemo.service.Impl.MessageImpl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
    {"sender_id":"","goods_id":"","receiver_id":"","type":"","message":""}
 */
@ServerEndpoint(value = "/channel/admin/{user_id}")
@Component  // 由 spring 扫描管理
public class adminChannel implements
        ApplicationContextAware { // 实现 ApplicationContextAware 接口， Spring 会在运行时注入 ApplicationContext

    // 用于存储用户连接和对应的用户 ID
    private static final Map<Session, String> userSessions = new ConcurrentHashMap<>();
    // 全局静态变量，保存 ApplicationContext
    static ApplicationContext applicationContext;
    // 声明需要的 Bean
    private com.example.tencentdemo.service.Impl.MessageImpl MessageImpl;

    // 保存 Spring 注入的 ApplicationContext 到静态变量
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        adminChannel.applicationContext = applicationContext;
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("user_id") String userId) {
        // 检查是否存在重复的userID
        if (userSessions.containsValue(userId)) {
            // 遍历userSessions以找到重复的userID对应的会话
            for (Map.Entry<Session, String> entry : userSessions.entrySet()) {
                if (entry.getValue().equals(userId)) {
                    // 移除上一个与重复userID关联的会话
                    Session previousSession = entry.getKey();
                    userSessions.remove(previousSession);
                    System.out.println("移除上一个与重复userID关联的会话: " + previousSession.getId());
                    break; // 找到第一个匹配的会话后即可退出循环
                }
            }
        }
        System.out.println("WebSocket连接开始: " + session.getId() + ", User ID: " + userId);
        userSessions.put(session, userId); // 将用户连接和用户 ID 关联起来
        System.out.println(userSessions);


    }

    // 当收到消息时触发
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("Received message: " + message);
        // 将字符串转化为Json对象
        JSONObject jsonObject = JSON.parseObject(message);
        // 提取出消息中的接收者id
        Object receiverId = jsonObject.get("receiver_id");

        // 检查接收者是否在线
        for (Session userSession : userSessions.keySet()) {
            Object userId = userSessions.get(userSession);
            if (userId.equals(receiverId)) {
                System.out.println("接收者在线");
                // 发送消息给接收者
                try {
                    userSession.getBasicRemote().sendText(message);
                    System.out.println("消息发送成功");
                } catch (IOException e) {
                    System.out.println("消息发送失败：" + e.getMessage());
                }
            }
        }
        // 执行数据库存储操作
        System.out.println("消息存入数据库");
        this.MessageImpl = adminChannel.applicationContext.getBean(MessageImpl.class);
        admin_message admin_message = com.example.tencentdemo.entity.admin_message.fromJson(message);
        MessageImpl.insertAdmin_Message(admin_message);

    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("WebSocket closed: " + session.getId());
        String userId = userSessions.remove(session); // 从 Map 中删除断开连接的用户
        System.out.println("User disconnected: " + userId);
    }


}